/*
 * @Author: xinyang3
 * @Date: 2021-11-08 14:53
 * @Descripttion: awesome description
 * @LastEditors: xinyang3
 * @LastEditTime: 2021-11-23 10:57
 */
import { MongoClient } from 'mongodb';

const user = 'admin123',
  pass = 'admin123';
const uri = `mongodb://${user}:${pass}@82.156.173.83:27017/?maxPoolSize=20&writeConcern=majority&authSource=blog`;
const dbName = 'blog';
const collections = [
  'blog',
  'user',
  'dictionary',
  'blog-views',
  'blog-comment',
];

let connect = null,
  db = null;

// 创建连接和db实例
function createConnect() {
  let promise = null;
  try {
    promise = new Promise((resolve, reject) => {
      const client = new MongoClient(uri);
      client.connect((e, cnt) => {
        if (e) {
          reject(e);
          console.error(e);
          client.close();
        } else {
          let idb = cnt.db(dbName);
          collections.forEach((collectionName) => {
            idb.collection(collectionName);
          });
          resolve({ connect: cnt, db: idb });
        }
      });
    });
  } catch (e) {
    console.error(e);
  }

  return promise;
}

// 获取唯一connect
async function getMongoConnect() {
  if (!connect || !db) {
    const result = await createConnect();
    connect = result.connect;
    db = result.db;
  }
  return { connect, db };
}

export { createConnect };
export default getMongoConnect;
